{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "\n",
    "filepath = \"detect_face/4.jpeg\"\n",
    "img = cv2.imread(filepath)  # 读取图片\n",
    "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转换灰色\n",
    "\n",
    "# OpenCV人脸识别分类器\n",
    "# 在使用OpenCV的人脸检测之前，需要一个人脸训练模型，格式是xml的，我们这里使用OpenCV提供好的人脸分类模型xml\n",
    "classifier = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n",
    "color = (0, 255, 0)  # 定义绘制颜色\n",
    "# 调用识别人脸\n",
    "faceRects = classifier.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\n",
    "if len(faceRects):  # 大于0则检测到人脸\n",
    "    for faceRect in faceRects:  # 单独框出每一张人脸\n",
    "        x, y, w, h = faceRect\n",
    "        # 框出人脸\n",
    "        cv2.rectangle(img, (x, y), (x + h, y + w), color, 2)\n",
    "        # 左眼\n",
    "        cv2.circle(img, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8),\n",
    "                   color)\n",
    "        # 右眼\n",
    "        cv2.circle(img, (x + 3 * w // 4, y + h // 4 + 30), min(w // 8, h // 8),\n",
    "                   color)\n",
    "        # 嘴巴\n",
    "        cv2.rectangle(img, (x + 3 * w // 8, y + 3 * h // 4),\n",
    "                      (x + 5 * w // 8, y + 7 * h // 8), color)\n",
    "\n",
    "cv2.imshow(\"image\", img)  # 显示图像\n",
    "c = cv2.waitKey(10)\n",
    "\n",
    "cv2.waitKey(0)\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
